package com.pms.init.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.espirit.eap.ValidationUtil;
import com.espirit.eap.manager.Dictionary;
import com.espirit.eap.manager.DictionaryService;
import com.espirit.eap.manager.I18n;
import com.espirit.eap.manager.I18nService;
import com.espirit.eap.manager.Menu;
import com.espirit.eap.manager.MenuService;
import com.espirit.eap.manager.SystemData;
import com.espirit.eap.manager.SystemDataService;
import com.espirit.eap.manager.TaskScheduler;
import com.espirit.eap.manager.processor.BizNodeInfo;
import com.espirit.eap.manager.workflow.WFAutoNode;
import com.espirit.eap.manager.workflow.WFPhase;
import com.espirit.eap.manager.workflow.WFTemplate;
import com.espirit.eap.pagelayout.FunctionButton;
import com.espirit.eap.pagelayout.Model;
import com.espirit.eap.pagelayout.ModelService;
import com.espirit.eap.pagelayout.Page;
import com.espirit.eap.pagelayout.PageUpgradeService;
import com.espirit.eap.sa.FieldPermissionType;
import com.espirit.eap.sa.ModelFieldPermission;
import com.espirit.eap.sa.PageFieldPermission;
import com.espirit.eap.sa.Privilege;
import com.espirit.eap.sa.PrivilegeService;
import com.espirit.eap.sa.ScopeType;
import com.espirit.eap.sa.Template;
import com.espirit.eap.sa.UserTemplate;
import com.espirit.eap.sa.UserTemplatePrivilege;
import com.espirit.eap.sa.WebsiteService;
import com.googlecode.cswish.model.ModelInfo;
import com.googlecode.cswish.oosearch.QLInfo;
import com.googlecode.cswish.struts.spring.BeanIntrospector;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.util.ClassUtil;
import com.pms.charge.ARItem;
import com.pms.eap.manager.Department;
import com.pms.eap.sa.User;
import com.pms.house.Building;
import com.pms.house.Garden;
import com.pms.house.House;
import com.pms.manager.AdjustChargeItem;
import com.pms.manager.DebitChargeItem;
import com.pms.manager.DebitChargeItemStandard;


/**
 * Manage DataBase
 * 	 
 * @author jerry.feng Date: 2008-10-24
 */
@Service
public class SaleDBAService extends DBAService {
	private static final Log logger = LogFactory.getLog(SaleDBAService.class);
	
	@Resource
	private BeanIntrospector beanIntrospector;
	
	@Resource
	protected MenuService menuService;
	
	@Resource
	protected GenericService genericService;
	
	@Resource
	private I18nService i18nService;
		
	@Resource
	protected ValidationUtil genericServiceUtil;
	
	
	@Resource
	private WebsiteService websiteService;
	
	@Resource
	private ModelService modelService;
	
	@Resource
	private PrivilegeService privilegeService;
	
	@Resource
	private PageUpgradeService pageUpgradeService;
	
	@Resource
	SystemDataService systemDataService;
	
	@Resource
	DictionaryService dictionaryService;
	
	// these model is shared by all websites
	private Set<String> sharedModel;
	
	
	@Override
	public void initDB(String initModel) {
		super.initDB(initModel);
		
		systemDataService.setValue(SystemData.ENABLE_SYSTEMLOG, "true");
		systemDataService.setValue(SystemData.FORCE_USE_SYSTEMLAYOUT, "true");
	}
	
	public SaleDBAService() {
		sharedModel = new HashSet<String>();
		sharedModel.add("espirit.eap.sa.user");
		sharedModel.add("espirit.eap.sa.template");
		sharedModel.add("espirit.eap.manager.department");
		sharedModel.add("espirit.eap.manager.menu");
		sharedModel.add("espirit.eap.pagelayout.page");
	}
	
	@Override
	public boolean init() {
		System.out.println("begin init data.................");
		initDB("create-drop");
		initModel();
		initModelInitData();
//		saveI18nData(eapI18nData);
		initSystemData();
		System.out.println("finished init data successfully!!!!!!");
		return true;
	}
	
	public boolean fastInit(){
		initDB("create-drop");
		initModel();
		initModelInitData();
		fastInitSystemData();
		return true;
	}
	
	public void fastInitSystemData() {
		initMenuData();
		initAllPrivileges();
		fastInitTemplate();
		initBizData();
	}
	
	@Override
	public void initSystemData() {
		initMenuData();
		initAllPrivileges();
		initDefaultTemplate();
		initBizData();
		
	}
	
	public void initModel() {
		super.builderModel("com.pms.init.base");
		super.builderModel("com.pms.init");
		
	}
	
	public void upgradeModel(){
		super.builderModel("com.pms.init.base");
		super.builderModel("com.pms.init");
	}
	
	@Override
	public void initModelInitData() {
		super.builderModelInitData("com.pms.init.base");
		super.builderModelInitData("com.pms.init");
	}
	
	public void initMenuData(){
		System.out.println("init menu data: ");
		long startTime = System.currentTimeMillis();
		String site = "pms";
		
		Menu menuProcess = menuService.createMenu("process","Processing","审批",null,site);
		Menu menuFinance = menuService.createMenu("finance","Finance","财务",null,site);
		Menu menuStat = menuService.createMenu("statistics","Statistics","统计分析",null,site);
		Menu menuManager = menuService.createMenu("manager","Administration","管理",null,site);
		
		//make menu sale
		
		//finance
		menuService.createMenu(ARItem.class, menuFinance,site);
		
		//make menu manager
		Menu menuManagerSecurity = menuService.createMenu("manager.security","Security","权限",menuManager,site);
		Menu menuManagerDefine = menuService.createMenu("manager.define","Definition","定义",menuManager,site);
		Menu menuManagerWorkFlow = menuService.createMenu("manager.workflow","Workflow","流程",menuManager,site);
		Menu menuHouseManager = menuService.createMenu("garden","Garden Info","楼宇信息",menuManager,site);
//		
		menuService.createMenu(User.class,menuManagerSecurity,site);
		menuService.createMenu(Template.class,menuManagerSecurity,site);
		menuService.createMenu(Department.class,menuManagerSecurity,site);
		menuService.createMenu(Menu.class,menuManagerSecurity,site);
		menuService.createMenu(Page.class,menuManagerSecurity,site);
		
		menuService.createMenu(House.class, menuHouseManager, site);
		menuService.createMenu(Building.class, menuHouseManager, site);
		menuService.createMenu(Garden.class, menuHouseManager, site);
		
		menuService.createMenu(WFPhase.class,menuManagerWorkFlow,site);
		menuService.createMenu(WFTemplate.class,menuManagerWorkFlow,site);

		menuService.createMenu(DebitChargeItem.class,menuManagerDefine,site);
		menuService.createMenu(DebitChargeItemStandard.class,menuManagerDefine,site);
		menuService.createMenu(AdjustChargeItem.class,menuManagerDefine,site);

		
		long endTime = System.currentTimeMillis();
		System.out.println("finished init menu data , init killed time(m) : " + (endTime - startTime)/60000);

	}
	
	
	
	ModelInfo mi = null;
	public void initAllPrivileges(){
		
		String m_add = "_add";
		String m_update = "_update";
		String m_delete = "deleteList";
		String m_search = "search";
		String m_export = "export";
		
		List<String> methods = new ArrayList<String>();
		methods.add(m_add);
		methods.add(m_update);
		methods.add(m_delete);
		methods.add(m_search);
		methods.add(m_export);
		
		List<ScopeType> scopes = new ArrayList<ScopeType>();
		scopes.add(ScopeType.Basic);
		scopes.add(ScopeType.Deep);
		scopes.add(ScopeType.Global);
		scopes.add(ScopeType.Local);
		
		addHousePrivilege(scopes, methods);
		addCommonPrivilege(scopes, methods);
		addManagerPrivilege(scopes, methods);
		addFinancePrivilege(scopes, methods);
		addStatPrivilege(scopes, methods);
		addProcessPrivilege(scopes, methods);
		addEapPrivilege(scopes, methods);
		
	}
	
	private List getPackageModels(String packageName){
		List<Model> models = (List<Model>) genericService.searchByQl(new QLInfo("from " 
				+ Model.class.getName() + " a where a.name like ? order by a.name", true, packageName + ".%"), true).getData();
		List<Model> results = new ArrayList<Model>();
		for(Model model : models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			Class clazz = ClassUtil.forName(fullModelName);
			if (clazz != null && clazz.getAnnotation(
					com.espirit.eap.annotation.DomainModel.class) == null) {
				continue;
			}
			results.add(model);
		}
		return results;
	}
	
	private String getI18nKey(String cnName, String enName){
		I18n i18n = i18nService.addI18n(cnName, enName);
		return i18n.getKey();
	}
	
	private void addCommonPrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("espirit.common");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			if (modelName.endsWith("netSearch")){
				addMethodGlobalPrivilege(modelName, "_searchWeb");
				addMethodGlobalPrivilege(modelName, "searchItem");
				addMethodGlobalPrivilege(modelName, "searchReadyResult");
				addMethodGlobalPrivilege(modelName, "addToMatch", getI18nKey("加入匹配", "AddToMatch"));
			} else if (modelName.endsWith("sysLog")){
				addSearchScopePrivilege(modelName, scopes);
				addMethodGlobalPrivilege(modelName, FunctionButton.PREADD);
			} else if (modelName.endsWith("hotPartItem")){
				addSearchGlobalPrivilege(modelName);
			} else if(modelName.endsWith("latestPartItem")){
				addSearchGlobalPrivilege(modelName);
			} else if (modelName.endsWith("smartSearch")){
				addPreSearchScopePrivilege(modelName, scopes );
				
				addMethodGlobalPrivilege(modelName, "addToCar");
				addMethodGlobalPrivilege(modelName, "switchTargetLayout");
				
			}  else if (modelName.endsWith("rfqMatchedItem")){
				addSearchScopePrivilege(modelName, scopes);
				addMethodGlobalPrivilege(modelName, FunctionButton.PREUPDATE);
				addMethodGlobalPrivilege(modelName, FunctionButton.DELETE);
				addMethodGlobalPrivilege(modelName, "_quote");
				addMethodGlobalPrivilege(modelName, "_addAvab");
				addMethodGlobalPrivilege(modelName, "_addFromCar");
				addMethodGlobalPrivilege(modelName, "needToCall");
				addMethodGlobalPrivilege(modelName, "searchByNeedToCallItems", getI18nKey("询价","Requiry"));
				addMethodGlobalPrivilege(modelName, "_generateOffer");
				addMethodGlobalPrivilege(modelName, "callComplete");
				addMethodGlobalPrivilege(modelName, "searchNeedToSelect");
				addMethodGlobalPrivilege(modelName, "searchSoiAllMatchedItems");
				addMethodGlobalPrivilege(modelName, "reAddSoi");
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
			} else if (modelName.endsWith("contacter")){
				for(String method : methods){
					addMethodScopePrivilege(modelName, method, scopes);
				}
			} else {
				for(String method : methods){
					addMethodGlobalPrivilege(modelName, method);
				}
			}
		}
	}
	
	private void addStatPrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("espirit.stat");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			if (modelName.toLowerCase().endsWith("accountpartitem")){
				addImportPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
				addCommonPrivilege(model, methods, scopes);
			} else {
				addSearchGlobalPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
			}
		}
	}
	
	
	private void addProcessPrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("espirit.process");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			addSearchGlobalPrivilege(modelName);
			addMethodGlobalPrivilege(modelName, FunctionButton.PREUPDATE);
			addMethodGlobalPrivilege(modelName, "_approve");
			
			addGetLayoutPrivilege(modelName);
		}
	}
	
	private void addHousePrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("pms.house");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			addCommonPrivilege(model, methods, scopes);
			addGetLayoutPrivilege(fullModelName);
		}
	}
	
	private void addEapPrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("pms.eap");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			for(String method : methods){
				addMethodGlobalPrivilege(modelName, method);
			}
			if (modelName.endsWith("partItem")){
				addImportPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, "showPartItemInfo");
				addGetLayoutPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, "showDetail");
				addMethodGlobalPrivilege(modelName, "showHomepage");
				addMethodGlobalPrivilege(modelName, "showList");
				addMethodGlobalPrivilege(modelName, "viewFile");
			}
			
			if (modelName.endsWith("privilege")){
				addMethodGlobalPrivilege(modelName, "applySelectedPrivileges");
			}
			
			if (modelName.endsWith("brand")){
				addGetLayoutPrivilege(modelName);
				addImportPrivilege(modelName);
			}
			if (modelName.endsWith("eccn")){
				addImportPrivilege(modelName);
			}
		}
	}
	
	private void addManagerPrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("pms.manager");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			for(String method : methods){
				addMethodGlobalPrivilege(modelName, method);
			}
		}
	}
	
	
	
	private void addFinancePrivilege(List<ScopeType> scopes, List<String> methods){
		List<Model> models = getPackageModels("espirit.finance");
		for(Model model: models){
			String modelName = model.getName();
			String fullModelName = beanIntrospector.getModelName(modelName);
			mi = beanIntrospector.getModelInfo(fullModelName);
			
			if (modelName.endsWith("aRItem") ){
				addSearchScopePrivilege(modelName, scopes);
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
				addMethodGlobalPrivilege(modelName, "off");
				addMethodGlobalPrivilege(modelName, "report");
				addMethodScopePrivilege(modelName, "searchByNeedToOffItems", scopes);
				
				addMethodScopePrivilege(modelName, FunctionButton.PREUPDATE, scopes);
				addMethodGlobalPrivilege(modelName, "_generateReceipt");
				addMethodGlobalPrivilege(modelName, "_generateInvoice");
			} else if (modelName.endsWith("aRItemOffed")){
				addSearchGlobalPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, "back");
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
			} else if (modelName.endsWith("aPItem")){
				addSearchScopePrivilege(modelName, scopes);
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
				addMethodGlobalPrivilege(modelName, "off");
				addMethodGlobalPrivilege(modelName, "report");
				addMethodScopePrivilege(modelName, "searchByNeedToOffItems", scopes);
				
				addMethodScopePrivilege(modelName, FunctionButton.PREUPDATE, scopes);
				addMethodGlobalPrivilege(modelName, "_generatePayment");
				addMethodGlobalPrivilege(modelName, "_generateInvoice");
			} else if (modelName.endsWith("aPItemOffed")){
				addSearchGlobalPrivilege(modelName);
				addMethodGlobalPrivilege(modelName, "back");
				addMethodGlobalPrivilege(modelName, FunctionButton.EXPORT);
			} else if (modelName.endsWith("receipt") ){
				for(String method : methods){
					addMethodGlobalPrivilege(modelName, method);
				}
				addMethodGlobalPrivilege(modelName, "report");
			} else if (modelName.endsWith("payment") ){
				for(String method : methods){
					addMethodGlobalPrivilege(modelName, method);
				}
				addMethodGlobalPrivilege(modelName, "report");
			} else {
				addCommonPrivilege(model, methods, scopes);
			}
			
			addGetLayoutPrivilege(modelName);


		}
	}
	
	private void addGetLayoutPrivilege(String modelName){
		addMethodGlobalPrivilege(modelName, "getLayout");
	}
	private void addCommonPrivilege(Model model,List<String> methods,List<ScopeType> scopes){
		String modelName = model.getName();
		if (mi.getProperty("owner") != null){
			for(String method : methods){
				addMethodScopePrivilege(modelName, method, scopes);
			}
		} else {
			for(String method : methods){
				addMethodGlobalPrivilege(modelName, method);
			}
		}
	}
	
	private void addImportPrivilege(String modelName){
		addMethodGlobalPrivilege(modelName, "_importFile");
	}
	
	private void addSearchGlobalPrivilege(String modelName){
		addMethodGlobalPrivilege(modelName, "search");
	}

	private void addPreSearchScopePrivilege(String modelName, List<ScopeType> scopes){
		addMethodScopePrivilege(modelName, "_search", scopes);
	}

	
	private void addSearchScopePrivilege(String modelName, List<ScopeType> scopes){
		addMethodScopePrivilege(modelName,"search",  scopes);
	}
	
	private void addMethodScopePrivilege(String modelName,String method , List<ScopeType> scopes){
		for(ScopeType scopeType : scopes){
			addMethodScopePrivile(modelName, method, scopeType);
		}
	}
	
	private void addMethodGlobalPrivilege(String modelName,String method){
		addMethodScopePrivile(modelName, method, ScopeType.Global);
	}
	
	private void addMethodGlobalPrivilege(String modelName,String method, String i18n){
		addMethodScopePrivile(modelName, method, ScopeType.Global, i18n);
	}
	
	public void addMethodScopePrivile(String modelSimpleName,String method ,ScopeType scopeType){
		addMethodScopePrivile(modelSimpleName, method, scopeType, null);
	}

	public void addMethodScopePrivile(String modelSimpleName,String method ,ScopeType scopeType, String i18n){
		privilegeService.addMethodScopePrivile(modelSimpleName, method, scopeType, i18n);
	}
	
	private void addBackPrivilege(String modelName){
		addMethodGlobalPrivilege(modelName, "back");
	}
	
	private void addGoNextPrivilege(String modelName){
		addMethodGlobalPrivilege(modelName, "_goNext");
	}
	
	public void fastInitTemplate(){
		User u_admin = new User();
		u_admin.setCode("admin");
		u_admin = genericService.searchAll(u_admin).getData(0);
		addAllPrivilege(u_admin.getLoginUser());
	}
	
	public void initDefaultTemplate(){
		System.out.println("init default privilege data....");
		
		String website = "espirit";

		Template t_admin = new Template();
		t_admin.setName("管理员");
		t_admin.setDescription("admin");
		t_admin = genericServiceUtil.checkAndAdd(t_admin);
		addAllPrivilege(t_admin);

		fastInitTemplate();
		
		Template t_fm = new Template();
		t_fm.setName("财务经理");
		t_fm.setDescription("Finance Manager");
		t_fm = genericServiceUtil.checkAndAdd(t_fm);
		setUtCategoryPrivilege(website, t_fm, "finance");
		
		System.out.println("finished init default privilege data.");
	}
	
	
	
	private void addModelFieldPrivilege(UserTemplate ut ,String modelSimpleName ,String[] restrictFields ,ScopeType scopeType ){
		for(String restrictField : restrictFields){
			ModelFieldPermission modelFieldPermission = new ModelFieldPermission();
			modelFieldPermission.setModelSimpleName(modelSimpleName);
			modelFieldPermission.setFieldName(restrictField);
			modelFieldPermission.setFieldPermissionType(FieldPermissionType.READWRITE);
			modelFieldPermission.setScopeType(scopeType);
			modelFieldPermission.setWriteScopeType(scopeType);
			modelFieldPermission.setUserTemplate(ut);
			ut.safeModelFieldPermissions().add(modelFieldPermission);
			
			genericService.merge(ut);
		}
	}
	
	private void addPageFieldPrivilege(Template template, String modelSimpleName, String method, String[] restrictFields  ){
		UserTemplatePrivilege utp = new UserTemplatePrivilege();
		Privilege privilege = new Privilege();
		privilege.setModelSimpleName(modelSimpleName);
		privilege.setMethod(method);
		utp.setUserTemplate(template);
		utp.setPrivilege(privilege);
		utp = genericService.searchAll(utp).getData(0);
		if (utp != null){
			for(String restrictField : restrictFields){
				PageFieldPermission pageFieldPermission = new PageFieldPermission();
				pageFieldPermission.setUserTemplatePrivilege(utp);
				pageFieldPermission.setFieldName(restrictField);
				pageFieldPermission.setFieldPermissionType(FieldPermissionType.NONE);
				pageFieldPermission.setScopeType(ScopeType.None);
				genericService.add(pageFieldPermission);
			}
		}
	}
	
	private void addAllPrivilege(UserTemplate ut){
		String website = "pms";
		setUtCategoryPrivilege(website, ut,  "common");
		setUtCategoryPrivilege(website, ut, "eap");
		setUtCategoryPrivilege(website, ut, "process");
		setUtCategoryPrivilege(website, ut, "stat");
		setUtCategoryPrivilege(website, ut, "house");
	}
	private Map<String ,Map<String ,List<Privilege>>> privileges = new HashMap<String ,Map<String ,List<Privilege>>>();
	
	private void setUtCategoryPrivilege(String website, UserTemplate ut,String category , ScopeType scopeType){
		setUtCategoryPrivilege(website, ut, category, scopeType, null);
	}
	
	private void setUtCategoryPrivilege(String website, UserTemplate ut,String category , ScopeType scopeType, List<String> notIncludedClass){
		System.out.println("init ut privilege data :" + ut.getName());
		String key = website + "." + category;
		Map<String ,List<Privilege>> privileges =  getCategoryPrivileges(key, notIncludedClass);
		for(String Key : privileges.keySet()){
			List<Privilege> maps = privileges.get(Key);
			if (maps.size() == 1){
				UserTemplatePrivilege utp = new UserTemplatePrivilege();
				utp.setPrivilege(maps.get(0));
				utp.setUserTemplate(ut);
				genericService.merge(utp);
				ut.safeUserTemplatePrivileges().add(utp);
			} else {
				for(Privilege privilege : maps){
					if (privilege.getScopeType().equals(scopeType)){
						UserTemplatePrivilege utp = new UserTemplatePrivilege();
						utp.setPrivilege(privilege);
						utp.setUserTemplate(ut);
						ut.safeUserTemplatePrivileges().add(utp);
						break;
					}
				}
			}
		}
		genericService.merge(ut);
	}
	
	protected void setUtCategoryPrivilege(String website, UserTemplate ut,String category){
		setUtCategoryPrivilege(website, ut, category,ScopeType.Global);
	}
	
	private Map<String,List<Privilege>> getCategoryPrivileges(String categoryKey, List<String> notIncludedClass){
		if (privileges.containsKey(categoryKey)){
			return privileges.get(categoryKey);
		} else {
			
			String prefix = categoryKey;
			if (prefix.equals("espirit.customerAgent")){  //special dealing,FIXME: better solution?
				prefix = "espirit.sale";
			}
			QLInfo qlInfo = new QLInfo("from " + Model.class.getName() 
					+ " a where a.name like '" + prefix + ".%'", false);
			List<Model> models = (List<Model>) genericService.searchByQl(qlInfo, true).getData();
			Map<String ,List<Privilege>> groupPrivileges = new HashMap<String , List<Privilege>>();
			for(Model dm : models){
				String fullModelName = beanIntrospector.getModelName(dm.getName());
				Class clazz = ClassUtil.forName(fullModelName);
				if (clazz != null && clazz.getAnnotation(
						com.espirit.eap.annotation.DomainModel.class) == null) {
					continue;
				}
				
				if (notIncludedClass != null && notIncludedClass.contains(clazz.getName())){
					continue;
				}
				
				Privilege model = new Privilege();
				model.setModelSimpleName(dm.getName());
				model = genericService.searchAll(model).getData(0);

				List<UserTemplatePrivilege> results =  new ArrayList<UserTemplatePrivilege>();
				String hql = "select a from Privilege a where a.modelSimpleName='" + dm.getName() + "' order by a.method ";
				List<Privilege> privieleges = genericService.searchByQl(new QLInfo(hql, true), false).getData();
				
				for(Privilege privilege : privieleges){
					String method = privilege.getMethod();
					if (categoryKey.equals("espirit.customerAgent") ){
						if (method.equals("getLayout")){
							continue;
						}
						
						
					}
					String key = dm.getName() + "#" + method;
					if (groupPrivileges.containsKey(key)){
						List<Privilege> mapPrivileges = groupPrivileges.get(key);
						mapPrivileges.add(privilege);
					} else {
						List<Privilege> mapPrivileges = new ArrayList<Privilege>();
						mapPrivileges.add(privilege);
						
						groupPrivileges.put(key, mapPrivileges);
					}
				}
			}
			return groupPrivileges;
		}
	}
	
	public void initBizData(){
		initTaskSchedulerData();
		resetPluginUpdateTime();
		initDictionaryData();
	}
	
	public void initUpgradeBizData(){
		initTaskSchedulerData();
		resetPluginUpdateTime();
		initDictionaryData();
	}
	
	private void resetPluginUpdateTime() {
		pageUpgradeService.resetUpgradeTime();
	}
	
	private void initDictionaryData(){
		dictionaryService.mergeByTypeValue(new Dictionary("单身公寓", "1", "houseType"));
		dictionaryService.mergeByTypeValue(new Dictionary("一房一厅", "2", "houseType"));
		dictionaryService.mergeByTypeValue(new Dictionary("两房一厅", "3", "houseType"));
		dictionaryService.mergeByTypeValue(new Dictionary("三房一厅", "4", "houseType"));
		dictionaryService.mergeByTypeValue(new Dictionary("四房一厅", "5", "houseType"));
		
		dictionaryService.mergeByTypeValue(new Dictionary("自主", "1", "houseStatus"));
		dictionaryService.mergeByTypeValue(new Dictionary("租用", "2", "houseStatus"));
		dictionaryService.mergeByTypeValue(new Dictionary("空置", "3", "houseStatus"));
	}
	
	
	private BizNodeInfo addBizNodeInfo(BizNodeInfo bizNodeInfo){
		BizNodeInfo search = new BizNodeInfo();
		search.setModelSimpleName(bizNodeInfo.getModelSimpleName());
		search.setMethod(bizNodeInfo.getMethod());
		search = genericService.searchAll(search).getData(0);
		if (search == null){
			return genericService.add(bizNodeInfo);
		}
		return search;
	}
	
	private WFAutoNode addAutoNodeInfo(WFAutoNode autoNode){
		WFAutoNode search = new WFAutoNode();
		search.setAction(autoNode.getAction());
		search = genericService.searchAll(search).getData(0);
		if (search == null){
			return genericService.add(autoNode);
		}
		return search;
	}
	
	private void initTaskSchedulerData() {
		// fix rate 1 hour
		checkAndAddTaskScheduler("Clean Invalid Login User",
				"com.googlecode.cswish.security.SafeManager.cleanInvalidLoginUser",
				"3600000", "每隔1小时");
		
		// 22:00 am every day (night)
		checkAndAddTaskScheduler("Backup DB",
				"com.espirit.eap.manager.DbBackupHistoryService.backupDb",
				"0 0 22 * * ?", "每晚10点");
	}
	
	private void checkAndAddTaskScheduler(String name, String command, String cond, String desc) {
		TaskScheduler example = new TaskScheduler();
		example.setName(name);
		TaskScheduler taskScheduler = genericService.searchAll(example).getData(0);
		if (taskScheduler == null) {
			taskScheduler = example;
		}
		
		taskScheduler.setCommand(command);
		taskScheduler.setCond(cond);
		taskScheduler.setActive(true);
		taskScheduler.setDescription(desc);
		genericService.merge(taskScheduler);
	}
	
	@Override
	public void initI18nData() {
	}
}